package tr.edu.yildiz.ce.dap.appagent.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import tr.edu.yildiz.ce.dap.appagent.exception.AgentDeploymentException;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public class DownloadService {
	
	public static void download(String url,String filePath) throws AgentDeploymentException{
		try{
			URL downloadUrl = new URL(url);
			File destinationFile = new File(filePath);
			if (!destinationFile.exists()){
				FileOutputStream fout = new FileOutputStream(new File(filePath));
				InputStream uis = downloadUrl.openStream();
				int r = -1;
				while ( (r=uis.read()) != -1){
					fout.write(r);
				}
				fout.close();
				uis.close();
			}
		}catch (MalformedURLException e) {
			throw new AgentDeploymentException("Url is not valid : " + url );
		}catch (IOException e) {
			throw new AgentDeploymentException("File can not be saved : " + filePath);
		}
	} 

}
